import axios from "../axios/axios";
import mutations from "@/store/mutations";
import router from "@/router";
import { getSession } from "@/utils/session";
import asyncRoute from "@/router/asyncRoute";
import { Notification } from "element-ui";

export default {
  state: () => {
    return {
      user: getSession("user") || null
    };
  },
  mutations: {
    [mutations.SET_USER](state, user) {
      state.user = user;
    }
  },
  actions: {
    login({ commit, state }, user) {
      return new Promise((resolve, reject) => {
        axios
            .post("/base/login", user)
          .then(res => {
            const { token, schoolCode, userType, stuUrl} = res;
            commit(mutations.SET_USER, {
              token,
              userType,
              schoolCode,
              stuUrl,
              ...res.loginUserInfo
            });

            commit(mutations.SET_MENU, res.menus);
            commit(mutations.SET_ASYNCROUTES);
            router.addRoutes(asyncRoute);
            resolve(true);
          })
          .catch(reject);
      });
    },
    exitLogin({ commit }) {
      for (const k in mutations) commit(mutations[k], null);
      router.push({ name: "Login" });
    },
    isCreatedByUser({ getters }, userCode) {
      if (getters.getUserAccount === userCode) return Promise.resolve(true);
      Notification.warning("只能操作本人创建的信息！");
      return Promise.resolve(false);
    }
  },
  getters: {
    getToken(state) {
      return state.user && state.user.token;
    },
    getUserType(state) {
      //1 teacher,2 super,3 admin ,4 student
      return state.user && state.user.userType;
    },
    getUserAccount(state) {
      return state.user && state.user.usercode;
    },
    getUserSchoolCode(state) {
      return state.user && state.user.schoolCode;
    }
  }
};
